<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container">
      <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="请输入名称"
                v-model="listQuery.name">
      </el-input>
      <el-button class="filter-item" style="margin-left: 5px;" type="primary" v-waves icon="el-icon-search"
                 @click="handleFilter">查询
      </el-button>
      <el-button v-if="base_drug_add" class="filter-item" style="margin-left: 10px;" @click="handleCreate"
                 type="primary" icon="edit">添加
      </el-button>
    </div>
    <el-table :key='tableKey' :data="list" v-loading="listLoading" element-loading-text="给我一点时间" border fit
              highlight-current-row style="width: 100%">
      <el-table-column align="center" label="药品名称">
        <template scope="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="药品别名">
        <template scope="scope">
          <span>{{ scope.row.nameAlias }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="药品简拼">
        <template scope="scope">
          <span>{{ scope.row.spell }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作">
        <template scope="scope">
          <el-button v-if="base_drug_upd" size="mini" type="primary"
                     @click="handleRule(scope.row)">规则
          </el-button>
          <el-button v-if="base_drug_upd" size="mini" type="success"
                     @click="handleUpdate(scope.row)">编辑
          </el-button>
          <el-button v-if="base_drug_del" size="mini" type="danger"
                     @click="handleDelete(scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div v-show="!listLoading" class="pagination-container">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                     :current-page.sync="listQuery.page"
                     :page-sizes="[10,20,30, 50]" :page-size="listQuery.limit"
                     layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>
    <!-- 药品规则弹框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="ruleDialogFormVisible">
      <el-form :model="form" :rules="rules" ref="form" label-width="120px">
        <el-form-item label="药品名称" prop="drugsName">
          <el-input
            placeholder="请输入内容"
            v-model="drugsName"
            :disabled="true">
          </el-input>
        </el-form-item>
        <el-form-item label="药品规则">
          <div class="line"></div>
        </el-form-item>
        <el-form-item v-for="(item, index) in rulesObj.drugRules" :key="item.key" :label="'< 规则' + (index+1) + ' >'"
                      class="condition">
          <div class="demo_container">
            <div class="demo-input-suffix">
              <span>规则类型：</span>
              <el-select v-model="item.type" clearable placeholder="请选择">
                <el-option
                  v-for="item in ruleType"
                  :key="item.num"
                  :label="item.desc"
                  :value="item.num">
                </el-option>
              </el-select>
            </div>
            <div class="demo-input-suffix">
              <span>规则等级：</span>
              <el-select v-model="item.level" clearable placeholder="请选择">
                <el-option
                  v-for="item in ruleLevel"
                  :key="item.num"
                  :label="item.desc"
                  :value="item.num">
                </el-option>
              </el-select>
            </div>
            <div class="demo-input-suffix">
              <span>类型目标名称：</span>
              <el-input
                placeholder="请输入内容"
                v-model="item.name">
              </el-input>
            </div>
            <div class="demo-input-suffix">
              <span>规则描述：</span>
              <el-input
                placeholder="请输入内容"
                v-model="item.description" type="textarea">
              </el-input>
            </div>
          </div>
          <el-button @click.prevent="removeDrugRules(item)" type="danger">删除规则</el-button>
        </el-form-item>
        <el-form-item label="用量规则">
          <div class="line"></div>
        </el-form-item>
        <el-form-item v-for="(item, index) in rulesObj.drugUsageRules" :key="item.key"
                      :label="'< 规则' + (index+1) + ' >'" class="condition">
          <div class="demo_container">
            <div class="demo-input-suffix">
              <span>每次用量：</span>
              <el-input
                placeholder="请输入内容"
                v-model="item.dose">
              </el-input>
            </div>
            <div class="demo-input-suffix">
              <span>用量单位：</span>
              <el-select v-model="item.doseUnit" clearable placeholder="请选择">
                <el-option
                  v-for="item in doseUnit"
                  :key="item.num"
                  :label="item.desc"
                  :value="item.num">
                </el-option>
              </el-select>
            </div>
            <div class="demo-input-suffix">
              <span>频次：</span>
              <el-input
                placeholder="请输入内容"
                v-model="item.freq">
              </el-input>
            </div>
            <div class="demo-input-suffix">
              <span>频次单位：</span>
              <el-select v-model="item.freqUnit" clearable placeholder="请选择">
                <el-option
                  v-for="item in freqUnit"
                  :key="item.num"
                  :label="item.desc"
                  :value="item.num">
                </el-option>
              </el-select>
            </div>
            <div class="demo-input-suffix">
              <span>人群：</span>
              <el-select v-model="item.people" clearable placeholder="请选择">
                <el-option
                  v-for="item in peopleType"
                  :key="item.num"
                  :label="item.desc"
                  :value="item.num">
                </el-option>
              </el-select>
            </div>
            <div class="demo-input-suffix">
              <span>用法：</span>
              <el-select v-model="item.usages" multiple clearable placeholder="请选择">
                <el-option
                  v-for="item in usageType"
                  :key="item.num"
                  :label="item.desc"
                  :value="item.num">
                </el-option>
              </el-select>
            </div>
            <div class="demo-input-suffix">
              <span>规则描述：</span>
              <el-input
                placeholder="请输入内容"
                v-model="item.description" type="textarea">
              </el-input>
            </div>
          </div>
          <el-button @click.prevent="removeDosageRules(item)" type="danger">删除规则</el-button>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDrugRules" type="success">新增药品规则</el-button>
        <el-button @click="addDosageRules" type="success">新增用量规则</el-button>
        <el-button type="primary" @click="saveRules()">提 交</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px">
        <el-form-item label="药品名称" prop="username">
          <el-input v-model="form.name" placeholder="药品名称"></el-input>
        </el-form-item>
        <el-form-item label="药品别名" prop="username">
          <el-input v-model="form.nameAlias" placeholder="药品别名"></el-input>
        </el-form-item>
        <el-form-item label="药品简拼" prop="username">
          <el-input v-model="form.spell" placeholder="药品别名"></el-input>
        </el-form-item>
        <el-form-item label="药品类型代码" prop="username">
          <el-select v-model="form.type" placeholder="请选择药品类型代码">
            <el-option v-for="item in dictOptions" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel('form')">取 消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="create('form')">确 定</el-button>
        <el-button v-else type="primary" @click="update('form')">修 改</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    addObj,
    delObj,
    fetchList,
    getDoseUnit,
    getDrugType,
    getDrugUsageType,
    getFreqUnit,
    getPeopleType,
    getRule,
    getRuleLevel,
    getUsageType,
    putObj,
    saveRules
  } from '@/api/pce/baseDrug'
  import { formatDate } from '@/api/pce/date'
  import waves from '@/directive/waves/index.js' // 水波纹指令
  import { mapGetters } from 'vuex'

  export default {
    name: 'table_base_drug',
    directives: {
      waves
    },
    data() {
      return {
        ruleType: [
          {
            num: 1,
            desc: '相互作用'
          },
          {
            num: 2,
            desc: '人群'
          },
          {
            num: 3,
            desc: '配伍禁忌'
          },
          {
            num: 4,
            desc: '用法'
          }
        ], // 所有规则类型
        peopleType: [], // 所有规则等级
        usageType: [], // 所有规则等级
        ruleLevel: [], // 所有规则等级
        doseUnit: [], // 所有用量规则
        freqUnit: [], // 所有频次规则
        rulesList: [], //  获取规则列表
        rulesObj: {
          drugId: '',
          drugName: '',
          drugRules: [],
          drugUsageRules: []
        },
        drugsName: '', // 药品名称
        list: null,
        total: null,
        listLoading: true,
        listQuery: {
          name: '',
          page: 1,
          limit: 20
        },
        rules: {},
        form: {},
        dialogFormVisible: false,
        ruleDialogFormVisible: false,
        dialogStatus: '',
        base_drug_edit: false,
        base_drug_add: false,
        base_drug_upd: false,
        base_drug_del: false,
        textMap: {
          rule: '管理规则明细',
          update: '编辑',
          create: '创建'
        },
        dictOptions: [
          {
            value: 1,
            label: '西药'
          },
          {
            value: 2,
            label: '中草药'
          },
          {
            value: 3,
            label: '中成药'
          },
          {
            value: 4,
            label: '疫苗'
          },
          {
            value: 5,
            label: '材料'
          },
          {
            value: 6,
            label: '其它'
          }
        ],
        tableKey:
          0
      }
    },
    computed: {
      ...mapGetters(['permissions'])
    },
    filters: {
      statusFilter(status) {
        const statusMap = {
          0: '有效',
          1: '无效'
        }
        return statusMap[status]
      },
      formatDate(time) {
        var date = new Date(time)
        return formatDate(date, 'yyyy-MM-dd hh:mm:ss')
      }
    },
    created() {
      this.getList()
      this.base_drug_edit = this.permissions['base_drug_edit']
      this.base_drug_add = this.permissions['base_drug_add']
      this.base_drug_upd = this.permissions['base_drug_upd']
      this.base_drug_del = this.permissions['base_drug_del']
    },
    methods: {
      // 提交按钮
      saveRules() {
        this.listLoading = true
        console.error(this.rulesObj)
        var data = this.rulesObj
        // 获取当前药品规则
        saveRules(data).then(response => {
          if (response.data) {
            this.ruleDialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '操作成功',
              type: 'success',
              duration: 2000
            })
          } else {
            this.$notify({
              title: '失败',
              message: '操作失败',
              type: 'fail',
              duration: 2000
            })
          }
          this.listLoading = false
          console.error(response.data)
        })
      },
      // 删除药品成分规则
      removeDrugRules(item) {
        var index = this.rulesObj.drugRules.indexOf(item)
        if (index !== -1) {
          this.rulesObj.drugRules.splice(index, 1)
        }
      },
      // 添加药品成分规则
      addDrugRules() {
        this.rulesObj.drugRules.push({
          description: '',
          level: 1,
          name: '',
          type: 1
        })
      },
      // 删除药品用量规则
      removeDosageRules(item) {
        var index = this.rulesObj.drugUsageRules.indexOf(item)
        if (index !== -1) {
          this.rulesObj.drugUsageRules.splice(index, 1)
        }
      },
      // 添加药品用量规则
      addDosageRules() {
        this.rulesObj.drugUsageRules.push({
          description: '',
          usages: [],
          people: 1,
          dose: 1,
          doseUnit: 1,
          freq: 1,
          freqUnit: 4
        })
      },
      getList() {
        this.listLoading = true
        fetchList(this.listQuery).then(response => {
          /*          this.list = response.data.content
            this.total = response.data.numberOfElements*/
          this.list = response.data.records
          this.total = response.data.total
          this.listLoading = false
        })
      },
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
      handleSizeChange(val) {
        this.listQuery.limit = val
        this.getList()
      },
      handleCurrentChange(val) {
        this.listQuery.page = val
        this.getList()
      },
      handleDelete(row) {
        delObj(row.id).then(response => {
          this.dialogFormVisible = false
          this.getList()
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
        })
      },
      // 药品规则
      handleRule(row) {
        // 获取当前药品规则
        getRule(row.id).then(response => {
          this.rulesObj = null
          if (response) {
            this.rulesObj = response.data.data
          }
          this.dialogStatus = 'rule'
          this.ruleDialogFormVisible = true
          this.drugsName = row.name
        })
        // 获取用量单位
        getDoseUnit(row.id).then(response => {
          if (response) {
            this.doseUnit = response.data
          }
        })
        // 获取频次单位
        getFreqUnit(row.id).then(response => {
          if (response) {
            this.freqUnit = response.data
          }
        })
        // 获取规则类型
        getRuleLevel(row.id).then(response => {
          if (response) {
            this.ruleLevel = response.data
          }
        })
        // 获取人群类型
        getPeopleType(row.id).then(response => {
          if (response) {
            this.peopleType = response.data
          }
        })
        // 获取用法类型
        getUsageType(row.id).then(response => {
          if (response) {
            this.usageType = response.data
          }
        })
        // 获取药品功用类型
        getDrugUsageType(row.id).then(response => {
        })
        // 获取药品类型
        getDrugType(row.id).then(response => {
        })
      },
      handleCreate() {
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.form = {}
      },
      handleUpdate(row) {
        this.form = Object.assign({}, row) // copy obj
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      create(formName) {
        const set = this.$refs
        set[formName].validate(valid => {
          if (valid) {
            addObj(this.form).then(() => {
              this.dialogFormVisible = false
              this.getList()
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 2000
              })
            })
          } else {
            return false
          }
        })
      },
      cancel(formName) {
        this.dialogFormVisible = false
        const set = this.$refs
        set[formName].resetFields()
      },
      update(formName) {
        const set = this.$refs
        set[formName].validate(valid => {
          if (valid) {
            this.dialogFormVisible = false
            this.form.password = undefined
            putObj(this.form).then(() => {
              this.dialogFormVisible = false
              this.getList()
              this.$notify({
                title: '成功',
                message: '修改成功',
                type: 'success',
                duration: 2000
              })
            })
          } else {
            return false
          }
        })
      }
    }
  }
</script>
<style>
  .demo_container {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
  }

  .demo-input-suffix {
    width: 48%;
    display: flex;
    margin-bottom: 10px;
  }

  .demo-input-suffix > span {
    display: block;
    min-width: 100px;
  }

  .line {
    width: 100%;
    height: 1px;
    margin-top: 18px;
    border-bottom: 2px dotted #e5e5e5;
  }
</style>
